import sys,os,socket

def usage():
	print >>sys.stderr,"Usage: %s nb_server"% os.path.split(sys.argv[0])[-1]

if __name__ == "__main__":
	nb_servers = 0
	try: nb_servers = int(sys.argv[1])
	except Exception,e: usage()
	processes = []
	if nb_servers < 1: raise SystemExit
	#------------
	master_port = 22000
	# 1st peer (master)
	master_result = os.spawnv(os.P_NOWAIT, "server.sh" , ("server.sh", str(master_port),))
	processes.append(master_result)
	ip_address =  socket.gethostbyname(socket.gethostname())
	# peers (in addition to master)	
	if nb_servers > 1:
			peer_port = master_port 
			for x in range(nb_servers-1):
				peer_port += 1
				import time
				time.sleep(2)
				processes.append(os.spawnv(os.P_NOWAIT, "server.sh", ("server.sh", str(master_port),ip_address,str(peer_port),)))
	#wait running processes
	while processes:
		for i in range(len(processes)):
			pi, st = os.waitpid(processes[i],0)  #, os.WNOHANG)
			print pi,st
			if pi == processes[i]:
				del processes[i]
				print 'pid', pi, 'status', st
				break
	#os.getloadavg()



